// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const { roomId, type, content } = event
  
  try {
    // 查找房间
    const room = await db.collection('rooms').where({
      roomId: roomId
    }).get()
    
    if (room.data.length === 0) {
      return {
        success: false,
        error: '房间不存在'
      }
    }
    
    const roomData = room.data[0]
    
    // 检查发送者权限
    const isPlayer = roomData.players.some(player => player.openid === wxContext.OPENID)
    if (!isPlayer) {
      return {
        success: false,
        error: '非房间成员'
      }
    }
    
    // 创建消息记录
    const message = {
      roomId: roomId,
      type: type, // system, player, game
      content: content,
      sender: wxContext.OPENID,
      createTime: db.serverDate()
    }
    
    // 保存消息到数据库
    await db.collection('messages').add({
      data: message
    })
    
    // 更新房间最后更新时间
    await db.collection('rooms').where({
      roomId: roomId
    }).update({
      data: {
        lastUpdateTime: db.serverDate()
      }
    })
    
    return {
      success: true,
      message: message
    }
  } catch (error) {
    console.error('发送消息失败:', error)
    return {
      success: false,
      error: error.message
    }
  }
} 